package com.longge;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-04-25 01:44
 */
public class NumIslands {

    public int numIslands(char[][] grid) {
        int m = grid.length;
        if (m == 0) return 0;
        int n = grid[0].length;
        UF uf = new UF(m * n);
        int[][] d = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        int islandsCount = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    islandsCount++;
                    for (int k = 0; k < 4; k++) {
                        int x = i + d[k][0];
                        int y = j + d[k][1];
                        if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1')
                            uf.union(x * n + y, i * n + j);
                    }
                }
            }
        }
        return uf.count() - (m * n - islandsCount);
    }
}
